//
//  ATUtil.m
//  ABCTime
//
//  Created by admin on 25/11/2017.
//  Copyright © 2017 100TAL. All rights reserved.
//

#import "ATUtil.h"
// ====================================================================================================== //
@implementation UIView (ATUtil)

@end
// ====================================================================================================== //

@implementation NSArray (ATUtil)
- (instancetype) at_safeObjectAtIndex:(NSInteger) index {
    if (index < self.count && index >= 0 && self.count > 0) {
        return [self objectAtIndex:index];
    }
    
    return nil;
}
@end

// ====================================================================================================== //
@implementation ATUtil

CGRect ATSCREEN_SCALE_RATIO_CENTER (CGRect iPadRect) {
    CGSize curScreenSize = [UIScreen mainScreen].bounds.size;
    CGSize targetImageSize = CGSizeMake(iPadRect.size.width * (curScreenSize.width / 1024), iPadRect.size.height * (curScreenSize.height / 768));
    
    CGFloat ratio = iPadRect.size.height / (targetImageSize.height);
    targetImageSize.width = iPadRect.size.width / ratio;
    targetImageSize.height = iPadRect.size.height / ratio;

    return CGRectMake(iPadRect.origin.x/ ATSCREEN_SCALE_RATIO(), iPadRect.origin.y/ATSCREEN_SCALE_RATIO(), targetImageSize.width, targetImageSize.height);
}

CGFloat ATSCREEN_SCALE_RATIO (void) {
    return 768/ATSCREEN_HEIGHT();
}

CGFloat ATSCREEN_HEIGHT (void) {
    return [[UIScreen mainScreen] bounds].size.height;
}

CGFloat ATSCREEN_WIDTH (void) {
    return [[UIScreen mainScreen] bounds].size.width;
}

+ (NSString *)p_iphoneSize {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        switch ((int)[[UIScreen mainScreen] nativeBounds].size.height) {
            case 1136:
                return ATiPhoneSize_5;
            case 1334:
                return ATiPhoneSize_6;
            case 2208:
                return ATiPhoneSize_6P;
            case 2436:
                return ATiPhoneSize_x;

            default:
                return @"not recognized";
        }
    } else {
        return @"not iphone";
    }
}

//获取Document路径
+ (NSString *)getDocumentPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return filePaths.firstObject;
}

//获取Library路径
+ (NSString *)getLibraryPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    return filePaths.firstObject;
}

//获取应用程序路径
+ (NSString *)getApplicationPath {
    return NSHomeDirectory();
}

//获取Cache路径
+ (NSString *)getCachePath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return filePaths.firstObject;
}

//获取Temp路径
+ (NSString *)getTempPath {
    return NSTemporaryDirectory();
}

+ (NSString *) at_resourcePathWithClass:(Class) bundleClass
                             bundleName:(NSString *) bundleName
                                subPath:(NSString *)subPath
                               fileName:(NSString *)fileName {
    
    NSBundle *resourceBundle = [self at_resourceBundleWithClass:bundleClass bundleName:bundleName];
    NSString *filePath;
    if (subPath && ![subPath isEqualToString:@""]) {
        filePath = [resourceBundle.bundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",subPath, fileName]];
    } else {
        filePath = [resourceBundle.bundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", fileName]];
    }
    
    if ([fileName isEqualToString:@""]) {
        filePath = $(@"%@/", filePath);
    } else if (!fileName) {
        filePath = filePath.stringByDeletingLastPathComponent;
        filePath = $(@"%@/", filePath);
    }

    return filePath;
}

+ (NSBundle *) at_resourceBundleWithClass:(Class) bundleClass
                               bundleName:(NSString *) bundleName {
    
    NSBundle *libraryBundle = [NSBundle bundleForClass:bundleClass];
    NSString *path = [libraryBundle pathForResource:bundleName ofType:@"bundle"];
    return [NSBundle bundleWithPath:path];
}



+ (NSString *)getiPhoneSize {
    return [self p_iphoneSize];
}

+ (BOOL)isBlackHairLeft {
    return ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft);
}

+ (NSString *)directoryPathInLibrary:(NSString *)directoryName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *directory = [paths[0] stringByAppendingPathComponent:directoryName];
    BOOL isDirectory = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:directory
                                              isDirectory:&isDirectory]
        || !isDirectory) {
        [[NSFileManager defaultManager] createDirectoryAtPath:directory
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:nil];
    }
    return directory;
}

//判断文件是否存在于某个路径中
+ (BOOL)fileIsExistOfPath:(NSString *)filePath {
    BOOL flag = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        flag = YES;
    } else {
        flag = NO;
    }
    return flag;
}

//从某个路径中移除文件
+ (BOOL)removeFileOfPath:(NSString *)filePath {
    BOOL flag = YES;
    NSFileManager *fileManage = [NSFileManager defaultManager];
    if ([fileManage fileExistsAtPath:filePath]) {
        if (![fileManage removeItemAtPath:filePath error:nil]) {
            flag = NO;
        }
    }
    return flag;
}

//从URL路径中移除文件
- (BOOL)removeFileOfURL:(NSURL *)fileURL {
    BOOL flag = YES;
    NSFileManager *fileManage = [NSFileManager defaultManager];
    if ([fileManage fileExistsAtPath:fileURL.path]) {
        if (![fileManage removeItemAtURL:fileURL error:nil]) {
            flag = NO;
        }
    }
    return flag;
}

//创建文件路径
+ (BOOL)creatDirectoryWithPath:(NSString *)dirPath {
    BOOL ret = YES;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:dirPath];
    if (!isExist) {
        NSError *error;
        BOOL isSuccess = [[NSFileManager defaultManager] createDirectoryAtPath:dirPath
                                                   withIntermediateDirectories:YES
                                                                    attributes:nil
                                                                         error:&error];
        if (!isSuccess) {
            ret = NO;
            NSLog(@"creat Directory Failed. errorInfo:%@",error);
        }
    }
    return ret;
}

//创建文件
+ (BOOL)creatFileWithPath:(NSString *)filePath {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL temp = [fileManager fileExistsAtPath:filePath];
    if (temp) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    NSString *dirPath = [filePath stringByDeletingLastPathComponent];
    isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creat File Failed. errorInfo:%@",error);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    return isSuccess;
}

//保存文件
+ (BOOL)saveFile:(NSString *)filePath withData:(NSData *)data {
    BOOL ret = NO;
    if (!data) {
        return ret;
    }
    ret = [self creatFileWithPath:filePath];
    if (ret) {
        ret = [data writeToFile:filePath atomically:YES];
        if (!ret) {
            NSLog(@"%s Failed",__FUNCTION__);
        }
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
    }
    return ret;
}

//追加写文件
+ (BOOL)appendData:(NSData *)data withPath:(NSString *)path {
    BOOL result = [self creatFileWithPath:path];
    if (result) {
        NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
        [handle seekToEndOfFile];
        [handle writeData:data];
        [handle synchronizeFile];
        [handle closeFile];
        return YES;
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
        return NO;
    }
}

//获取文件
+ (NSData *)getFileData:(NSString *)filePath {
    NSData *fileData = nil;
    @autoreleasepool {
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
        fileData = [handle readDataToEndOfFile];
        [handle closeFile];
    }
    return fileData;
}

//读取文件
+ (NSData *)getFileData:(NSString *)filePath
             startIndex:(long long)startIndex
                 length:(NSInteger)length {
    NSData *data = nil;
    @autoreleasepool {
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
        [handle seekToFileOffset:startIndex];
        data = [handle readDataOfLength:length];
        [handle closeFile];
    }
    return data;
}

//移动文件
+ (BOOL)moveFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"Error: fromPath Not Exist");
        return NO;
    }
    if (![fileManager fileExistsAtPath:toPath]) {
        NSLog(@"Error: toPath Not Exist");
        return NO;
    }
    NSString *headerComponent = [toPath stringByDeletingLastPathComponent];
    if ([self creatFileWithPath:headerComponent]) {
        return [fileManager moveItemAtPath:fromPath toPath:toPath error:nil];
    } else {
        return NO;
    }
}

//拷贝文件
+(BOOL)copyFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"Error: fromPath Not Exist");
        return NO;
    }
    if (![fileManager fileExistsAtPath:toPath]) {
        NSLog(@"Error: toPath Not Exist");
        return NO;
    }
    NSString *headerComponent = [toPath stringByDeletingLastPathComponent];
    if ([self creatFileWithPath:headerComponent]) {
        return [fileManager copyItemAtPath:fromPath toPath:toPath error:nil];
    } else {
        return NO;
    }
}

//获取文件夹下文件列表
+ (NSArray *)getFileListInFolderWithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileListInFolderWithPathFailed, errorInfo:%@",error);
    }
    return fileList;
}

//获取文件大小
+ (long long)getFileSizeWithPath:(NSString *)path {
    unsigned long long fileLength = 0;
    NSNumber *fileSize;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([self fileIsExistOfPath:path]){
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
        if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
            fileLength = [fileSize unsignedLongLongValue];
        }
    }
    return fileLength;
}

//获取文件创建时间
+ (NSString *)getFileCreatDateWithPath:(NSString *)path {
    NSString *date = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    date = [fileAttributes objectForKey:NSFileCreationDate];
    return date;
}

//获取文件所有者
+ (NSString *)getFileOwnerWithPath:(NSString *)path {
    NSString *fileOwner = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName];
    return fileOwner;
}

//获取文件更改日期
+ (NSString *)getFileChangeDateWithPath:(NSString *)path {
    NSString *date = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    date = [fileAttributes objectForKey:NSFileModificationDate];
    return date;
}

+ (NSString *)hexStringFromBytes:(const unsigned char *)bytes length:(NSInteger)length {
    const char *hexChars = "0123456789ABCDEF";
    char *chars = malloc(length * 2);
    char *s = chars;
    NSUInteger i = length;
    while (i--) {
        *s++ = hexChars[*bytes >> 4];
        *s++ = hexChars[*bytes & 0xF];
        bytes++;
    }
    NSString *str = [[NSString alloc] initWithBytesNoCopy:chars
                                                   length:length * 2
                                                 encoding:NSASCIIStringEncoding
                                             freeWhenDone:YES];
    return str;
}

+ (BOOL)isiPhoneSize_3_5 {
    return ATSCREEN_WIDTH() == 480.0;
}

+ (BOOL)isiPhoneSize_4_0 {
    return ATSCREEN_WIDTH() == 568.0;
}

+ (BOOL)isiPhoneSize_4_7 {
    return ATSCREEN_WIDTH() == 667.0;
}

+ (BOOL)isiPhoneSize_5_5 {
    return ATSCREEN_WIDTH() == 736.0;
}

+ (BOOL)isiPad {
    
    NSString *deviceType = [UIDevice currentDevice].model;
    
    return [deviceType isEqualToString:@"iPad"];
}

// 目前iPhone刘海屏都是使用iPhone X
+ (BOOL)isiPhoneX {
    return ATSCREEN_WIDTH() == 812.0;
}

+ (BOOL)isiPhoneXR {
    return (ATSCREEN_WIDTH() == 812.0) && ([UIScreen mainScreen].scale == 2);
}
@end
